package com.jiedeng.controller.index;

import com.jiedeng.controller.MessageController;
import com.jiedeng.controller.Rst;
import com.jiedeng.dao.*;
import com.jiedeng.entity.PeriodMune;
import com.jiedeng.entity.ResponsibilityCrop;
import com.jiedeng.entity.SpecMune;
import com.jiedeng.mapper.TaskMapper;
import com.jiedeng.model.*;
import com.jiedeng.util.DatetimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 任务管理
 *
 * @author zhouyb
 * 2018/4/13.
 */
@RestController
@Scope("prototype")
@RequestMapping("/taskManage")
public class TaskManageController {
    @Autowired
    MessageController messageController;
    @Autowired
    ICheckRepository checkRepository;
    @Autowired
    ICheckItemRepository iCheckItemRepository;
    @Autowired
    IFileRecordRepository fileRecordRepository;
    @Autowired
    ITaskRepository taskRepository;
    @Autowired
    IPeriodRepository periodRepositoty;
    @Autowired
    ISpecRepository specRepository;
    @Autowired
    IPersonRepository personRepository;
    @Autowired
    ICheckItemRuleRepository checkItemRuleRepository;
    @Autowired
    ICorpRepository corpRepository;
    @Autowired
    ICheckCountRepository checkCountRepository;
    @Autowired
    TaskMapper taskMapper;
    @Autowired
    IProjectPersonRepository projectPersonRepository;
//    @Value("${photo.url}")
//    private String photoUrl;

    /**
     * 查询check表 联查文件表和问题库
     *
     * @param taskId
     * @return
     */
    @RequestMapping("findCheckBytaskId")
    public List<Check> findCheckBytaskId(String taskId) {
        List<Check> checks = checkRepository.findByTaskIdOrderByCheckTimeDesc(taskId);
        List<Check> checkList = new ArrayList<Check>(10);
        for (Check check : checks) {
            if (check.isPub()) {
                List<FileRecord> records = fileRecordRepository.findByCheckId(check.getId());
                check.setFileRecords(records);
                if (check.getCheckItemId() != 0) {
                    Optional<CheckItem> checkItems = iCheckItemRepository.findById(check.getCheckItemId());
                    if (checkItems != null && checkItems.isPresent()) {
                        check.setCheckItem(checkItems.get());
                        checkList.add(check);
                    }
                } else {
                    checkList.add(check);
                }
            }
        }
        return checkList;
    }

    /**
     * 新增任务
     *
     * @param projectId      项目id
     * @param stageID        stageid
     * @param caption        描述
     * @param taskCorpId     任务单位id
     * @param taskPersonId   任务人员id
     * @param startTime      开始时间
     * @param endTime        结束时间
     * @param excutePersonId 人员id
     * @param pubPersonId    发布人
     * @param pubCorpId      发布单位
     * @return rst
     */
    @RequestMapping("addTaskEntity")
    public Rst addTaskEntity(String projectId, String stageID, String caption, String taskCorpId, String taskPersonId, String startTime, String endTime, String excutePersonId, String pubPersonId, String pubCorpId, String propId) {
        Rst rst = new Rst();
        try {
            Task task = new Task();
            String taskId = UUID.randomUUID().toString();
            task.setId(taskId);
            task.setPubCorpId(Long.parseLong(pubCorpId));
            task.setPubPersonId(Long.parseLong(pubPersonId));
        /*    task.setCloseCorpId(Long.parseLong(pubCorpId));
            task.setClosePersonId(Long.parseLong(pubPersonId));*/
            task.setProjectId(Integer.parseInt(projectId));
            task.setStageID(Long.parseLong(stageID));
            task.setCaption(caption);
            task.setTaskCorpId(Long.parseLong(taskCorpId));
            task.setPropId(Integer.valueOf(propId));
            task.setTaskPersonId(Long.parseLong(taskPersonId));
            task.setCreateTime(new Date());
            task.setStartTime(DatetimeUtil.formartDate("yyyy-MM-dd HH:mm:ss", startTime, 0));
            task.setEndTime(DatetimeUtil.formartDate("yyyy-MM-dd HH:mm:ss", endTime, 0));
            task.setExcutePersonId(excutePersonId);
            task.setExcuteTime(new Date());
            task.setVerify(true);
            taskRepository.save(task);
            addProjectPerson(Long.valueOf(projectId), taskPersonId, 501);
            addProjectPerson(Long.valueOf(projectId), excutePersonId, 502);
            String params = "projectId#" + projectId + "*taskId#" + taskId;
            messageController.saveMsg(taskPersonId, null, "1", task.getId(), params);
            rst.setResultCode(0);
            rst.setMsg("OK");
        } catch (Exception e) {
            rst.setResultCode(1);
            rst.setMsg("Mysql Error");
        }
        return rst;
    }

    /**
     * 签发审核
     *
     * @param taskId
     * @param agreest 是否同意
     * @return
     */
    @RequestMapping(value = "/issueOperation", method = RequestMethod.GET)
    public Rst issueOperation(String taskId, final boolean agreest) {
        Rst rst = new Rst();
        rst.setResultCode(0);
        if (StringUtils.isEmpty(taskId)) {
            rst.setMsg("任务id不能为空！");
        } else {
            Task task = taskRepository.getOne(taskId);
            if (agreest) {
                task.setVerify(true);
                if (task.getExcutePersonId() != null) {
                    String[] personIds = task.getExcutePersonId().split(",");
                    if (personIds != null && personIds.length > 0) {
                        for (int i = 0; i < personIds.length; i++) {
                            messageController.saveMsg(personIds[i], null, "1", taskId, null);
                        }
                    }
                }
            } else {
                task.setVerify(false);
            }
            taskRepository.save(task);
            rst.setMsg("OK");
        }
        return rst;
    }

    /**
     * 添加项目人员表
     *
     * @param projectId
     * @param personIds
     * @param postId
     */
    public void addProjectPerson(long projectId, String personIds, long postId) {
        if (StringUtils.isEmpty(personIds)) {
            return;
        }
        String[] personId = personIds.split(",");
        List<ProjectPerson> projectPeopleList = projectPersonRepository.findByProjectIdAndPostId(Long.valueOf(projectId), postId);
        for (ProjectPerson projectPerson : projectPeopleList) {
            projectPersonRepository.deleteById(projectPerson.getId());
        }
        for (String pId : personId) {
            ProjectPerson projectPerson = new ProjectPerson();
            projectPerson.setPostId(postId);
            projectPerson.setPersonId(Long.valueOf(pId));
            projectPerson.setProjectId(projectId);
            projectPersonRepository.save(projectPerson);
        }
    }

    /**
     * 新增检查项
     *
     * @param expressionDesc      检查内容
     * @param expressionDescPath  检查图片路径
     * @param checkItemId         检查项id
     * @param personId            用户id
     * @param taskId              任务id
     * @param expressionDescPath2
     * @param expressionDescPath3
     * @return
     */
    @RequestMapping("addCheckEntity")
    public Rst addCheckEntity(String expressionDesc, String expressionDescPath, String checkItemId, String personId, String taskId, String isCloseFile, String expressionDescPath2, String expressionDescPath3) {
        Rst rst = new Rst();
        try {
            Task task = taskRepository.getOne(taskId);
            Check check = new Check();
            String checkId = UUID.randomUUID().toString();
            check.setId(checkId);
            check.setProjectId(task.getProjectId());
            //check.setFileRecords(null);
            //check.setCloseFile(true);
            check.setCheckTime(new Date());
            check.setCheckPersonId(Long.parseLong(personId));
            check.setTaskId(taskId);
            check.setPub(true);
            check.setExamPersonId(task.getTaskPersonId());
            if (!StringUtils.isEmpty(checkItemId)) {
                check.setCheckItemId(Long.parseLong(checkItemId));
            }
            check.setExpressionDesc(expressionDesc);
            if ("1".equals(isCloseFile)) {
                check.setCloseFile(true);
            } else {
                check.setCloseFile(false);
            }
            checkRepository.save(check);
            //int num = 1;
            if (!StringUtils.isEmpty(expressionDescPath)) {
                addFileRecords(checkId, expressionDescPath, true, Long.parseLong(personId), 0, 1);
                //num++;
            }
            if (!StringUtils.isEmpty(expressionDescPath2)) {
                addFileRecords(checkId, expressionDescPath2, true, Long.parseLong(personId), 0, 2);
                //num++;
            }
            if (!StringUtils.isEmpty(expressionDescPath3)) {
                addFileRecords(checkId, expressionDescPath3, true, Long.parseLong(personId), 0, 3);
                //num++;
            }
            rst.setResultCode(0);
            rst.setMsg("OK");
        } catch (Exception e) {
            rst.setResultCode(1);
            rst.setMsg("Mysql Error");
        }
        return rst;
    }

    /**
     * 新增文件
     *
     * @param checkId      检查id
     * @param path         路径
     * @param checkOrClose 检查还是整改
     * @param addPersonId  用户id
     * @param sortId       排序
     * @param num          排序
     */
    public void addFileRecords(String checkId, String path, boolean checkOrClose, long addPersonId, int sortId, int num) {
        FileRecord fileRecord = new FileRecord();
        fileRecord.setId(UUID.randomUUID().toString());
        fileRecord.setCheckId(checkId);
        fileRecord.setCheckClose(checkOrClose);
        fileRecord.setType(1);
        fileRecord.setRecorder(addPersonId);
        fileRecord.setrTime(new Date());
//        if (path == null ||"".equals(path)) {
//            path=photoUrl;
//        }
        if (path != null && !"".equals(path)) {
            String suffix = path.substring(path.lastIndexOf(".") + 1);
            fileRecord.setFileType(suffix);
            fileRecord.setOldPhotoPath(path);
        }
        fileRecord.setIndate(new Date());
        fileRecord.setSortId(sortId);
        fileRecord.setNum(num);
        fileRecordRepository.save(fileRecord);
    }

    /**
     * 获取所有检查项-1.检查专业
     *
     * @return SpecMune集合
     */
    @RequestMapping(value = "getSpecMune", method = RequestMethod.GET)
    public List<SpecMune> getSpecMune() {
        List<SpecMune> specMuneList = new ArrayList<>();
        List<Spec> specList = specRepository.findAll();
        for (Spec spec : specList) {
            SpecMune node = new SpecMune();
            node.setSpec(spec);
            findAllParents(node);
            specMuneList.add(node);
        }
        return specMuneList;
    }

    /**
     * 获取所有检查项-2.工序
     *
     * @param specMune
     */
    public void findAllParents(SpecMune specMune) {
        List<PeriodMune> treesParent = new ArrayList<PeriodMune>();
        List<Period> periods = periodRepositoty.findBySpecId(specMune.getSpec().getId());
        for (Period p : periods) {
            PeriodMune node = new PeriodMune();
            node.setPeriod(p);
            getPeriodChildren(node);
            treesParent.add(node);
        }
        specMune.setPeriodMune(treesParent);
        //return treesParent;
    }

    /**
     * 获取所有检查项-3.工序 or 检查项
     *
     * @param p
     */
    private void getPeriodChildren(PeriodMune p) {
        List<PeriodMune> treesParent = new ArrayList<PeriodMune>();
        List<Period> periods = periodRepositoty.findByParent(p.getPeriod().getId());
        if (periods != null && periods.size() > 0) {
            for (Period period : periods) {
                PeriodMune treeNode = new PeriodMune();
                treeNode.setPeriod(period);
                treesParent.add(treeNode);
                getPeriodChildren(treeNode);
            }
            p.setPeriodChildren(treesParent);
        } else {
            List<CheckItem> itemList = iCheckItemRepository.findByPeriodIdAndIsVisible(p.getPeriod().getId(), true);
            p.setCheckItemChildren(itemList);
        }
    }
    /**
     * 获取所有检查项-1.检查专业
     *
     * @return SpecMune集合
     */
    @RequestMapping(value = "getSpecMuneNew", method = RequestMethod.GET)
    public List<SpecMune> getSpecMuneNew(String taskId) {
        Task task = taskRepository.getOne(taskId);

        List<SpecMune> specMuneList = new ArrayList<>();
        List<Spec> specList = specRepository.findSpecGetPropId( task.getPropId());
        for (Spec spec : specList) {
            SpecMune node = new SpecMune();
            node.setSpec(spec);
            findAllParentsNew(node,task.getPropId());
            specMuneList.add(node);
        }
        return specMuneList;
    }
    /**
     * 获取所有检查项-2.工序
     *
     * @param specMune
     */

    public void findAllParentsNew(SpecMune specMune,Integer propId) {
        List<PeriodMune> treesParent = new ArrayList<PeriodMune>();
        List<Period> periods = periodRepositoty.findBySpecIdAndPropId(specMune.getSpec().getId(),propId);
        for (Period p : periods) {
            PeriodMune node = new PeriodMune();
            node.setPeriod(p);
            getPeriodChildrenNew(node,propId);
            treesParent.add(node);
        }
        specMune.setPeriodMune(treesParent);
        //return treesParent;
    }
    /**
     * 获取所有检查项-3.工序 or 检查项
     *
     * @param p
     */
    private void getPeriodChildrenNew(PeriodMune p,Integer propId) {
        List<PeriodMune> treesParent = new ArrayList<PeriodMune>();
        List<Period> periods = periodRepositoty.findByParentAndPropId(p.getPeriod().getId(),propId);
        if (periods != null && periods.size() > 0) {
            for (Period period : periods) {
                PeriodMune treeNode = new PeriodMune();
                treeNode.setPeriod(period);
                treesParent.add(treeNode);
                getPeriodChildrenNew(treeNode,propId);
            }
            p.setPeriodChildren(treesParent);
        } else {
            List<CheckItem> itemList = iCheckItemRepository.findByPeriodIdAndIsVisibleAndPropId(p.getPeriod().getId(), true,propId);
//            List<CheckItem> itemList = iCheckItemRepository.findByPeriodIdAndIsVisible(p.getPeriod().getId(), true);
            p.setCheckItemChildren(itemList);
        }
    }
    /**
     * 开具整改
     *
     * @param taskId       任务id
     * @param taskCorpId   任务单位id
     * @param taskPersonId 任务人员id
     * @param completeTime 时间
     * @return rst
     */
    @RequestMapping("setChange")
    public Rst setChange(String taskId, String taskCorpId, String taskPersonId, String completeTime) {
        Rst rst = new Rst();
        try {
            int x = selectNotCheckCountNum(taskId);
            if (x > 0) {
                rst.setResultCode(1);
                rst.setMsg("存在未评分数据");
                return rst;
            }
            Long corpId = Long.parseLong(taskCorpId);
            Long personId = Long.parseLong(taskPersonId);
            // 更改check表
            List<Check> checks = checkRepository.findByTaskId(taskId);
            for (int i = 0; i < checks.size(); i++) {
                checks.get(i).setCloseCorpId(corpId);
                checks.get(i).setClosePersonId(personId);
                // completeTime
                checkRepository.save(checks.get(i));
            }
            // 更改任务状态
            Task task = taskRepository.getOne(taskId);
            task.setId(taskId);
            task.setDraft(false);
            task.setVerify(true);
            task.setClose(true);
            task.setCloseDo(false);
            task.setDo(false);
            task.setCloseCorpId(corpId);
            task.setClosePersonId(personId);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            task.setCloseTime(format.parse(completeTime));
            taskRepository.save(task);
            // 插入t_Project_Person
            ProjectPerson projectPerson = new ProjectPerson();
            projectPerson.setPersonId(personId);
            projectPerson.setProjectId(task.getProjectId());
            addProjectPerson(task.getProjectId(), personId + "", 602);
            // 查询单位责任岗位
            //Person person = personRepository.getOne(personId);
            //projectPerson.setPostId(person.getPostId());
            rst.setResultCode(0);

            rst.setMsg("OK");
        } catch (Exception e) {
            rst.setResultCode(1);
            rst.setMsg("Mysql Error");
        }
        return rst;
    }

    /**
     * 删除检查
     *
     * @param checkIds 检查id
     * @return rst
     */
    @RequestMapping("deleteCheck")
    public Rst deleteCheck(String checkIds) {
        Rst rst = new Rst();
        try {
            String[] ids = checkIds.split(",");
            for (String id : ids) {
                checkRepository.deleteById(id);
            }
            rst.setResultCode(0);
            rst.setMsg("OK");
        } catch (Exception e) {
            rst.setResultCode(1);
            rst.setMsg("Mysql Error");
        }
        return rst;
    }

    /**
     * 整改
     *
     * @param checkId             检查id
     * @param personId            人员id
     * @param closeMemo           描述
     * @param expressionDescPath  图1
     * @param expressionDescPath2 图2
     * @param expressionDescPath3 图3
     * @param delPhotoIds         删除图片id
     * @return Rst
     */
    @RequestMapping("addCheckChange")
    public Rst addCheckChange(String checkId, String personId, String closeMemo, String expressionDescPath, String expressionDescPath2, String expressionDescPath3, String delPhotoIds) {
        Rst rst = new Rst();
        try {
            Check check = checkRepository.getOne(checkId);
            check.setCloseMemo(closeMemo);
            check.setClose(true);
            check.setCloseMark(true);
            checkRepository.save(check);
            deleteFilePhoto(delPhotoIds);
            //int num = 1;
            if (!StringUtils.isEmpty(expressionDescPath)) {
                for (int i = 1; i < 4; i++) {
                    if (checkFile(checkId, false, i)) {
                        continue;
                    }
                    addFileRecords(checkId, expressionDescPath, false, Long.parseLong(personId), 0, i);
                    break;
                }
                //num++;
            }
            if (!StringUtils.isEmpty(expressionDescPath2)) {
                for (int i = 1; i < 4; i++) {
                    if (checkFile(checkId, false, i)) {
                        continue;
                    }
                    addFileRecords(checkId, expressionDescPath2, false, Long.parseLong(personId), 0, i);
                    break;
                }
                //addFileRecords(checkId, expressionDescPath2, false, Long.parseLong(personId), 0, 2);
                //num++;
            }
            if (!StringUtils.isEmpty(expressionDescPath3)) {
                for (int i = 1; i < 4; i++) {
                    if (checkFile(checkId, false, i)) {
                        continue;
                    }
                    addFileRecords(checkId, expressionDescPath3, false, Long.parseLong(personId), 0, i);
                    break;
                }
                //addFileRecords(checkId, expressionDescPath3, false, Long.parseLong(personId), 0, 3);
                //num++;
            }
//            for (int i = 1; i < 4; i++) {
//                if (checkFile(checkId, false, i)) {
//                    continue;
//                }
//                addFileRecords(checkId, null, false, Long.parseLong(personId), 0, i);
//                break;
//            }
            rst.setResultCode(0);
            rst.setMsg("OK");
        } catch (Exception e) {
            e.printStackTrace();
            rst.setResultCode(1);
            rst.setMsg("Mysql Error");
        }
        return rst;
    }

    /**
     * 判断是否存在
     *
     * @param checkId
     * @param checkOrClose
     * @param num
     * @return
     */
    public boolean checkFile(String checkId, boolean checkOrClose, int num) {
        FileRecord fileRecord = fileRecordRepository.findByCheckIdAndCheckCloseAndNum(checkId, checkOrClose, num);
        if (fileRecord == null) {
            return false;
        }
        return true;
    }

    /**
     * 整改提交
     *
     * @param taskId 任务id
     * @return rst
     */
    @RequestMapping("changeSubmit")
    public Rst changeSubmit(String taskId) {
        Rst rst = new Rst();
        try {
            // 更改任务状态
            Task task = taskRepository.getOne(taskId);
            task.setId(taskId);
            task.setDraft(false);
            task.setVerify(true);
            task.setClose(true);
            task.setCloseDo(true);
            task.setDo(false);
            taskRepository.save(task);
            rst.setResultCode(0);
            rst.setMsg("OK");
        } catch (Exception e) {
            rst.setResultCode(1);
            rst.setMsg("Mysql Error");
        }
        return rst;
    }

    /**
     * 闭环
     *
     * @param taskId 任务id
     * @return rst
     */
    @RequestMapping("taskClose")
    public Rst taskClose(String taskId) {
        Rst rst = new Rst();
        try {
            // 更改任务状态
            Task task = taskRepository.getOne(taskId);
            task.setDo(true);
            taskRepository.save(task);
            rst.setResultCode(0);
            rst.setMsg("OK");
        } catch (Exception e) {
            rst.setResultCode(1);
            rst.setMsg("Mysql Error");
        }
        return rst;
    }

    /**
     * 打回提交
     *
     * @param taskId 任务id
     * @return rst
     */
    @RequestMapping("/submitReturn")
    public Rst isReturn(String taskId, String reason) {
        Rst rst = new Rst();
        try {
            // 更改任务状态
            Task task = taskRepository.getOne(taskId);
            task.setCloseDo(false);
            task.setCloseMemo(reason);
            taskRepository.save(task);
            rst.setResultCode(0);
            rst.setMsg("OK");
        } catch (Exception e) {
            rst.setResultCode(1);
            rst.setMsg("Mysql Error");
        }
        return rst;
    }

    /**
     * 评分查找责任单位
     *
     * @param checkId
     * @param checkItemRuleId
     * @return
     */
    @RequestMapping("/findResponsibilityCrop")
    public List<ResponsibilityCrop> findResponsibilityCrop(String checkId, String checkItemRuleId) {
        Check check = checkRepository.getOne(checkId);
        if (check != null && check.getCheckItemId() != 0) {
            List<ResponsibilityCrop> cropList =
                    taskMapper.findResponsibilityCropList(check.getProjectId(), check.getCheckItemId(), Long.valueOf(checkItemRuleId), checkId);
            if (cropList != null && cropList.size() > 0) {
                return cropList;
            }
        }
        return null;
    }

    /**
     * 评分查找责任单位人
     *
     * @param checkId
     * @param corpId
     * @param postId
     * @return
     */
    @RequestMapping("/findResponsibilityPerson")
    public List<Person> findResponsibilityPerson(String checkId, String corpId, String postId) {
        Check check = checkRepository.getOne(checkId);
        List<Person> cropList = new ArrayList<>(10);
        if (check != null && check.getCheckItemId() != 0 && !StringUtils.isEmpty(corpId)) {
            cropList = taskMapper.findResponsibilityPersonList(check.getProjectId(), Long.valueOf(corpId), Long.valueOf(postId), checkId);
            if (cropList != null && cropList.size() > 0) {
                return cropList;
            }
        }
        return cropList;
    }

    /**
     * 评分
     *
     * @param responsibilityCorpPersonIds 各级别单位人员集合  CheckItemRuleId-corpId-personId,
     * @param checkId
     * @param scoreNum                    得分
     * @param deductionNum                扣分
     */
    @RequestMapping("/addCheckCountEntitys")
    public Rst addCheckCountEntitys(String responsibilityCorpPersonIds, String checkId, String scoreNum, String deductionNum) {
        Rst rst = new Rst();
        try { //根据',' 拆分出 CheckItemRuleId-corpId-personId 1-2-3
            String[] idsArray = responsibilityCorpPersonIds.split(",");
            checkCountRepository.deleteByCheckId(checkId);
            for (String ids : idsArray) {
                String[] id = ids.split("-");
                long checkItemRuleId = Long.valueOf(id[0]);
                long corpId = Long.valueOf(id[1]);
                long personId = Long.valueOf(id[2]);
                if (corpId == 0) {
                    continue;
                }
                CheckCount checkCount = new CheckCount();

                CheckItemRule checkItemRule = checkItemRuleRepository.getOne(checkItemRuleId);

                /*  List<CheckCount> checkCountList=  checkCountRepository.findByCheckIdAndCorpIdAndPostIdAndPersonIdAndCorpWeightLevel(checkId,corpId,checkItemRule.getPostId(),personId,checkItemRule.getCorpWeightLevel());*/
              /*  if(checkCountList!=null&&checkCountList.size()>0){
                    checkCount=checkCountList.get(0);
                }else{*/
                checkCount.setId(UUID.randomUUID().toString());
                checkCount.setCheckId(checkId);
                checkCount.setCorpWeightLevel(checkItemRule.getCorpWeightLevel());
                checkCount.setCorpPropId(checkItemRule.getCorpPropId());
                checkCount.setPostWeightLevel(checkItemRule.getPostWeightLevel());
                checkCount.setPostId(checkItemRule.getPostId());
                Corp corp = corpRepository.getOne(corpId);
                checkCount.setCorpId(corpId);
                checkCount.setCorpCaption(corp.getCaption());
                checkCount.setPersonId(personId);
                if (personId != 0) {
                    Person person = personRepository.getOne(personId);
                    checkCount.setName(person.getName());
                } else {
                    checkCount.setName("");
                }
                //}
                if ("主要责任单位".equals(checkItemRule.getCorpWeightLevel())) {
                    if (!StringUtils.isEmpty(checkItemRule.getWeighting())) {
                        checkCount.setScoring(deductionNum);
                        checkCount.setScoring1(null);
                    } else {
                        checkCount.setScoring(null);
                        checkCount.setScoring1(scoreNum);
                    }
                }
                if ("次要责任单位".equals(checkItemRule.getCorpWeightLevel())) {
                    double deduction = 0;
                    if (!StringUtils.isEmpty(deductionNum)) {
                        deduction = Double.parseDouble(deductionNum) / 2.0;
                    }
                    double score = 0;
                    if (!StringUtils.isEmpty(scoreNum)) {
                        score = Double.parseDouble(scoreNum) / 2.0;
                    }
                    if (!StringUtils.isEmpty(checkItemRule.getWeighting())) {
                        checkCount.setScoring1(null);
                        checkCount.setScoring(deduction + "");
                    } else {
                        checkCount.setScoring(null);
                        checkCount.setScoring1(score + "");
                    }
                }
                if ("相关责任单位".equals(checkItemRule.getCorpWeightLevel())) {
                    double deduction = 0;
                    if (!StringUtils.isEmpty(deductionNum)) {
                        deduction = Double.parseDouble(deductionNum) / 4.0;
                    }
                    double score = 0;
                    if (!StringUtils.isEmpty(scoreNum)) {
                        score = Double.parseDouble(scoreNum) / 4.0;
                    }
                    if (!StringUtils.isEmpty(checkItemRule.getWeighting())) {
                        checkCount.setScoring(deduction + "");
                        checkCount.setScoring1(null);
                    } else {
                        checkCount.setScoring(null);
                        checkCount.setScoring1(score + "");
                    }
                }
                checkCountRepository.save(checkCount);
            }
            rst.setResultCode(0);
            rst.setMsg("OK");
        } catch (Exception e) {
            rst.setResultCode(1);
            rst.setMsg("Mysql Error");
            e.printStackTrace();
        }
        return rst;
    }

    /**
     * 修改check
     *
     * @param checkId
     * @param personId
     * @param expressionDesc
     * @param delPhotoId
     * @param expressionDescPath
     * @param expressionDescPath2
     * @param expressionDescPath3
     * @return
     */
    @RequestMapping("/editCheckEntity")
    public Rst editCheckEntity(String checkId, String personId, String expressionDesc, String delPhotoId, String expressionDescPath, String expressionDescPath2, String expressionDescPath3) {
        Rst rst = new Rst();
        try {
            Check check = checkRepository.getOne(checkId);
            check.setExpressionDesc(expressionDesc);
            checkRepository.save(check);
            deleteFilePhoto(delPhotoId);
           /* if (!StringUtils.isEmpty(expressionDescPath)) {
                addFileRecords(checkId, expressionDescPath, true, Long.parseLong(personId), 0, 1);
            }
            if (!StringUtils.isEmpty(expressionDescPath2)) {
                addFileRecords(checkId, expressionDescPath2, true, Long.parseLong(personId), 0, 2);
            }
            if (!StringUtils.isEmpty(expressionDescPath3)) {
                addFileRecords(checkId, expressionDescPath3, true, Long.parseLong(personId), 0, 3);
            }*/
            if (!StringUtils.isEmpty(expressionDescPath)) {
                for (int i = 1; i < 4; i++) {
                    if (checkFile(checkId, true, i)) {
                        continue;
                    }
                    addFileRecords(checkId, expressionDescPath, true, Long.parseLong(personId), 0, i);
                    break;
                }
                //num++;
            }
            if (!StringUtils.isEmpty(expressionDescPath2)) {
                for (int i = 1; i < 4; i++) {
                    if (checkFile(checkId, true, i)) {
                        continue;
                    }
                    addFileRecords(checkId, expressionDescPath2, true, Long.parseLong(personId), 0, i);
                    break;
                }
                //addFileRecords(checkId, expressionDescPath2, false, Long.parseLong(personId), 0, 2);
                //num++;
            }
            if (!StringUtils.isEmpty(expressionDescPath3)) {
                for (int i = 1; i < 4; i++) {
                    if (checkFile(checkId, true, i)) {
                        continue;
                    }
                    addFileRecords(checkId, expressionDescPath3, true, Long.parseLong(personId), 0, i);
                    break;
                }
                //addFileRecords(checkId, expressionDescPath3, false, Long.parseLong(personId), 0, 3);
                //num++;
            }
//            for (int i = 1; i < 4; i++) {
//                if (checkFile(checkId, true, i)) {
//                    continue;
//                }
//                addFileRecords(checkId, null, true, Long.parseLong(personId), 0, i);
//                break;
//            }
            rst.setResultCode(0);
            rst.setMsg("OK");
        } catch (Exception e) {
            rst.setResultCode(1);
            rst.setMsg("Mysql Error");
        }
        return rst;
    }

    /**
     * 删除照片
     *
     * @param delPhotoIds
     */
    public void deleteFilePhoto(String delPhotoIds) {
        if (!StringUtils.isEmpty(delPhotoIds)) {
            String[] delPhotoId = delPhotoIds.split(",");
            for (String s : delPhotoId) {
                if (s.indexOf("seizeASeat") > -1) {
                    continue;
                }
                fileRecordRepository.deleteById(s);
            }
        }

    }

    /**
     * 查看未评分的check数
     *
     * @param taskId
     * @return
     */
    @RequestMapping("selectNotCheckCountNum")
    public int selectNotCheckCountNum(String taskId) {
        if (taskId != null) {
            return checkCountRepository.selectNotCheckCountNum(taskId);
        } else {
            return -1;
        }
    }
}
